package org.csu.canteen.persistence;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.*;
import org.csu.canteen.entity.CartItem;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface CartItemMapper extends BaseMapper<CartItem> {
    // 查询购物车中是否存在该商品
    @Select("SELECT COUNT(*) FROM cart_item WHERE username = #{username} AND item_id = #{itemid}")
    int exists(@Param("username") String username, @Param("itemid") String itemid);

    // 更新购物车中商品数量
    @Update("UPDATE cart_item SET number = number + #{number} WHERE username = #{username} AND item_id = #{itemid}")
    void updateNumber(@Param("username") String username, @Param("itemid") String itemid, @Param("number") int number);

    // 插入新的购物车商品
    /*@Insert("INSERT INTO cart_item (username, item_id, number) VALUES (#{username}, #{itemid}, #{number})")
    void insert(@Param("username") String username, @Param("itemid") String itemid, @Param("number") int number);*/

    @Select("SELECT c.*, i.* FROM cart_item c LEFT JOIN item i ON c.item_id = i.item_id WHERE c.username = #{username}")
    @Results({
            @Result(property = "itemId", column = "item_id"),
            @Result(property = "number", column = "number"),
            @Result(property = "item", column = "item_id", one = @One(select = "org.csu.canteen.mapper.ItemMapper.getItemById"))
    })
    List<CartItem> getCartByUsername(String username);

}
